<template>
  <div class="content">
    <!-- <div class="qwe" v-if="jisflag" @click="dialogVisible = true">
      <i class="el-icon-plus"></i>
    </div> -->
    <div class="qwe" v-if="jisflag" @click="daodialogVisible = true">
      <i class="el-icon-plus"></i>
    </div>
    <div class="qaz">
      <div class="boxs" v-for="item of cont" :key="item.id">
        <div @click="z(item)" class="zxc">
          <luyin class="content1" :luyinItem="item" />
        </div>
      </div>
    </div>
    <div v-if="jisflag">
      <el-table :data="cont" border>
        <el-table-column prop="label" label="教学周期"></el-table-column>
        <el-table-column prop="lecturer" label="讲师"> </el-table-column>
        <el-table-column prop="counsellor" label="辅导员"> </el-table-column>
        <el-table-column prop="category" label="录音类别"> </el-table-column>
        <el-table-column prop="is_audit" label="是否审核">
          <template slot-scope="scope">
            <el-tag :type="scope.row.is_audit ? 'success' : 'danger'">{{
              scope.row.is_audit ? "已审核" : "未审核"
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="create_data" label="提交时间">
          <template slot-scope="scope">
            {{ scope.row.create_data | formatDate }}
          </template>
        </el-table-column>
        <el-table-column prop="avatar" label="录音文件" width="300px">
          <template slot-scope="scope">
            <span v-if="scope.row.avatar != '' && scope.row.avatar != null">
              <div style="width: 300px; height: 50px">
                <video
                  controls
                  name="media"
                  style="width: 100%; height: 100%; object-fit: fill"
                >
                  <source :src="url + scope.row.avatar" type="audio/wav" />
                </video>
              </div>
            </span>
            <span v-else>暂未上传录音</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150px">
          <template slot-scope="scope">
            <span v-if="!scope.row.is_audit">
              <el-tooltip
                class="item"
                effect="dark"
                content="通过"
                placement="top"
              >
                <el-button
                  type="primary"
                  icon="el-icon-check"
                  circle
                  @click="successvoice(scope.row)"
                ></el-button
              ></el-tooltip>
              <el-tooltip
                class="item"
                effect="dark"
                content="不通过"
                placement="top"
              >
                <el-button
                  type="success"
                  icon="el-icon-error"
                  circle
                  @click="refusevoice(scope.row)"
                ></el-button
              ></el-tooltip>
            </span>
            <span v-else>
              <el-tag v-if="scope.row.audit_status == 1">待审核</el-tag>
              <el-tag type="success" v-if="scope.row.audit_status == 2"
                >通过</el-tag
              >
              <el-tag type="info" v-if="scope.row.audit_status == 3"
                >不通过</el-tag
              >
            </span>

            <el-tooltip
              class="item"
              effect="dark"
              content="删除"
              placement="top"
            >
              <el-button
                type="success"
                icon="el-icon-error"
                circle
                @click="removevoiceById(scope.row)"
              ></el-button
            ></el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog
      title="导入or录制"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
    >
      <el-switch
        v-model="value1"
        active-text="导入音频"
        inactive-text="录制音频"
      >
      </el-switch>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="value1 ? (daodialogVisible = true) : (ludialogVisible = true)"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <el-dialog
      title="导入音频"
      :visible.sync="daodialogVisible"
      width="30%"
      :before-close="daohandleClose"
    >
      <el-select
        v-model="addform.category"
        placeholder="请选择沟通方式"
        clearable
      >
        <el-option
          v-for="item in categoryoptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select>
      <br />
      <span style="display: inline-block; margin: 25px 0px">
        <label>是否为重点关注学生:</label>
        <input type="text" style="display: inline-block;width:200px" v-model="addform.focus" placeholder="是否为重点关注学生(0,1,是,否)"
      /></span>
      <el-upload
        class="upload-demo"
        drag
        :headers="header"
        :data="addform"
        action="http://101.34.188.212:8001/api/Voice"
        multiple
        :auto-upload="false"
        ref="voiceFile"
        :on-success="uploadSuccess"
        name="voice-file"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      </el-upload>
      <span slot="footer" class="dialog-footer">
        <el-button @click="daodialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="daoru">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="录制音频"
      :visible.sync="ludialogVisible"
      width="30%"
      :before-close="luhandleClose"
    >
      <el-select
        v-model="addform.category"
        placeholder="请选择沟通方式"
        clearable
      >
        <el-option
          v-for="item in categoryoptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select>
      <!-- <Button @click="getPermission()" style="margin: 1vw"
        >获取麦克风权限</Button
      > -->
      <Button type="info" @click="startRecorder()" style="margin: 1vw"
        >开始录音</Button
      >
      <Button type="info" @click="pauseRecorder()" style="margin: 1vw"
        >暂停录音</Button
      >
      <Button type="info" @click="stopRecorder()" style="margin: 1vw"
        >结束录音</Button
      >
      <!-- <Button type="info" @click="getRecorder()" style="margin: 1vw"
      >获取录音信息</Button
    > -->
      <Button type="info" @click="downPCM()" style="margin: 1vw"
        >下载PCM</Button
      >

      <Button type="info" @click="downWAV()" style="margin: 1vw"
        >下载WAV</Button
      >
      <!-- <Button type="info" @click="getMp3Data()" style="margin: 1vw"
      >下载MP3</Button
    > -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="ludialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="luzhi">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Recorder from "js-audio-recorder";
import { addVoice, editVoiceItem, removeVoice } from "network/api/voice";
import luyin from "@/components/luyin";
import { getHeader } from "utils/login";

const lamejs = require("lamejs");

const recorder = new Recorder({
  sampleBits: 16, // 采样位数，支持 8 或 16，默认是16

  sampleRate: 48000, // 采样率，支持 11025、16000、22050、24000、44100、48000，根据浏览器默认值，我的chrome是48000

  numChannels: 1, // 声道，支持 1 或 2， 默认是1

  // compiling: false,(0.x版本中生效,1.x增加中) // 是否边录边转换，默认是false
});
recorder.onprogress = function (params) {
  function throttle(callback, duration = 1000) {
    console.log("123");
    var lastTime = new Date().getTime();
    return function () {
      var now = new Date().getTime();
      if (now - lastTime > duration) {
        console.log("456");
        callback();
        lastTime = now;
      }
    };
  }
  throttle(function () {
    console.log("调用了一次");
  });

  // console.log("--------------START---------------");

  // console.log("录音时长(秒)", params.duration);

  // console.log("录音大小(字节)", params.fileSize);

  // console.log("录音音量百分比(%)", params.vol);

  // console.log("当前录音的总数据([DataView, DataView...])", params.data);

  // console.log("--------------END---------------");
};

export default {
  props: ["cont", "zxczxfasdgaaaa", "hgh", "hahaha"],
  watch: {
    "this.cont": function () {
      console.log(this.cont, 456);
      this.a = this.cont;
    },
  },
  components: {
    luyin,
  },
  created() {
    const token = window.sessionStorage.getItem("token");
    this.headers.Authorization = "Bearer " + token;
    this.a = this.cont;
    this.header = getHeader();
  },
  mounted() {
    console.log(this.$props.cont);
    this.a = this.cont;
  },
  data() {
    return {
      editform: {
        is_audit: true,
        auditpeople: "",
        auditpeople_id: null,
        audit_status: null,
        audit_remark: "",
      },
      url: "http://101.34.188.212:8001/",
      // url: "http://127.0.0.1:8000/",
      headers: {
        Authorization: "",
      },
      header: null,
      dialogVisible: false,
      value1: true,
      daodialogVisible: false,
      ludialogVisible: false,
      jisflag: false,
      a: [],
      addform: {
        student: null,
        category: "",
        focus: null,
      },
      categoryoptions: [
        { value: "导员=>家长", label: "导员=>家长" },
        { value: "学生=>家长", label: "学生=>家长" },
      ],
    };
  },
  filters: {
    formatDate: function (value) {
      let date = new Date(value);
      let y = date.getFullYear();
      let MM = date.getMonth() + 1;
      MM = MM < 10 ? "0" + MM : MM;
      let d = date.getDate();
      d = d < 10 ? "0" + d : d;
      let h = date.getHours();
      h = h < 10 ? "0" + h : h;
      let m = date.getMinutes();
      m = m < 10 ? "0" + m : m;
      let s = date.getSeconds();
      s = s < 10 ? "0" + s : s;
      return y + "-" + MM + "-" + d;
    },
  },
  methods: {
    async successvoice(row) {
      if (sessionStorage.getItem("username")) {
        this.editform.auditpeople = sessionStorage.getItem("username");
      } else {
        this.editform.auditpeople = "admin";
      }
      this.editform.auditpeople_id = sessionStorage.getItem("userid");
      this.editform.audit_status = 2;
      this.editform.audit_remark = "通过描述信息";
      const res = await editVoiceItem(row.id, this.editform);
      console.log(res, 5555);
      if (res) {
        this.editform = {
          is_audit: true,
          auditpeople: "",
          auditpeople_id: null,
          audit_status: null,
          audit_remark: "",
        };
        let avatar = "";
        // let xindex = null
        this.cont.forEach((item, index) => {
          if (item.id == res.id) {
            avatar = item.avatar;
            // xindex = index
          }
        });
        // let cont1 = JSON.stringify(this.cont)
        // let cont2 = JSON.parse(cont1)
        res.rank = 4;
        res.label = res.TeachingTime;
        res.avatar = avatar;
        // cont2[xindex] = res
        // this.cont=cont2
        this.hgh(res);
      }
    },
    async refusevoice(row) {
      if (sessionStorage.getItem("username")) {
        this.editform.auditpeople = sessionStorage.getItem("username");
      } else {
        this.editform.auditpeople = "admin";
      }
      this.editform.auditpeople_id = sessionStorage.getItem("userid");
      this.editform.audit_status = 3;
      this.editform.audit_remark = "不通过描述信息";
      const res = await editVoiceItem(row.id, this.editform);
      if (res) {
        this.editform = {
          is_audit: true,
          auditpeople: "",
          auditpeople_id: null,
          audit_status: null,
          audit_remark: "",
        };
        let avatar = "";
        this.cont.forEach((item, index) => {
          if (item.id == res.id) {
            avatar = item.avatar;
          }
        });
        res.rank = 4;
        res.label = res.TeachingTime;
        res.avatar = avatar;
        this.hgh(res);
      }
    },
    uploadSuccess(res, file, fileList) {
      if (res.status == "Yes") {
        this.daodialogVisible = false;
        this.ludialogVisible = false;
        this.dialogVisible = false;
        res.data.rank = 4;
        res.data.label = res.data.TeachingTime;
        this.hgh(res.data);
        this.$message.success(res.msg);
      } else {
        this.$message.error(res.msg);
      }
      console.log(111, res);
    },
    daoru() {
      // this.$refs.addFormRef1.validate(async (valid) => {
      // if (!valid) return;addform.category"
      if (
        this.addform.category == "" ||
        this.addform.category == undefined ||
        this.addform.category == null
      ) {
        this.$message.error("请选择语音类型");
        return;
      } else if (
        this.addform.focus == "" ||
        this.addform.focus == undefined ||
        this.addform.focus == null
      ) {
        this.$message.error("请选择输入是否为重点关注学生");
        return;
      }
      this.$refs.voiceFile.submit();

      // });
    },
    z(a) {
      if (a.rank === 4) return;
      if (a.rank === 3) {
        this.jisflag = true;
        this.addform.student = a.id;
      } else {
        this.jisflag = false;
        this.addform.student = null;
      }
      // this.$refs.tree.store.nodesMap[5].expanded = true;
      // console.log( this.$parent.data,5)
      // this.$parent.data = a.children;
      // console.log( this.$parent.data,6)
      // this.$parent.zxczxfasdgaaaa(a.children)
      // this.$emit('zxczxfasdgaaaa',a.children)
      this.zxczxfasdgaaaa(a.children, a);
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },
    daohandleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },
    luhandleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },
    async luzhi() {
      let toltime = recorder.duration; //录音总时长
      let fileSize = recorder.fileSize; //录音总大小
      if (toltime < 5) {
        if (toltime == 0) {
          alert("请录制音频");

          this.pauseRecorder();
          console.log(toltime);
          return;
        }
        // else {
        //   alert("录制不可以少于一分钟");

        //   this.pauseRecorder();
        // }
      }
      var pcm = recorder.getWAVBlob();
      let formData = new FormData();
      // formData.append("voice-file", pcm);
      formData.append("voice-file", pcm);
      formData.append("student", this.addform.student);
      formData.append("category", this.addform.category);
      const res = await addVoice(formData);
      if (res) {
        this.daodialogVisible = false;
        this.ludialogVisible = false;
        this.dialogVisible = false;
        res.rank = 4;
        res.label = res.TeachingTime;
        this.hgh(res);
      }
      console.log(111, res);
    },
    /**

* 获取录音文件

* */

    getRecorder() {
      let toltime = recorder.duration; //录音总时长

      let fileSize = recorder.fileSize; //录音总大小

      //录音结束，获取取录音数据

      let PCMBlob = recorder.getPCMBlob(); //获取 PCM 数据

      let wav = recorder.getWAVBlob(); //获取 WAV 数据

      let channel = recorder.getChannelData(); //获取左声道和右声道音频数据
      console.log(toltime, fileSize, "1111111111111");
    },

    convertToMp3(wavDataView) {
      // 获取wav头信息
      const wav = lamejs.WavHeader.readHeader(wavDataView); // 此处其实可以不用去读wav头信息，毕竟有对应的config配置

      const { channels, sampleRate } = wav;

      const mp3enc = new lamejs.Mp3Encoder(channels, sampleRate, 128);
      console.log(mp3enc);
      // 获取左右通道数据

      const result = recorder.getChannelData();

      const buffer = [];

      const leftData =
        result.left &&
        new Int16Array(result.left.buffer, 0, result.left.byteLength / 2);

      const rightData =
        result.right &&
        new Int16Array(result.right.buffer, 0, result.right.byteLength / 2);

      const remaining = leftData.length + (rightData ? rightData.length : 0);

      const maxSamples = 1152;

      for (let i = 0; i < remaining; i += maxSamples) {
        const left = leftData.subarray(i, i + maxSamples);

        let right = null;

        let mp3buf = null;

        if (channels === 2) {
          right = rightData.subarray(i, i + maxSamples);

          mp3buf = mp3enc.encodeBuffer(left, right);
        } else {
          mp3buf = mp3enc.encodeBuffer(left);
        }

        if (mp3buf.length > 0) {
          buffer.push(mp3buf);
        }
      }

      const enc = mp3enc.flush();

      if (enc.length > 0) {
        buffer.push(enc);
      }

      return new Blob(buffer, { type: "audio/mp3" });
    },

    /**

* 文件格式转换 wav-map3

* */

    getMp3Data() {
      const mp3Blob = this.convertToMp3(recorder.getWAV());

      recorder.download(mp3Blob, "recorder", "mp3");
    },

    /**

* 下载录音文件

* */

    //下载pcm

    downPCM() {
      //这里传参进去的时文件名

      recorder.downloadPCM("voice-file");
    },

    //下载wav

    downWAV() {
      //这里传参进去的时文件名

      recorder.downloadWAV("voice-file");
    },

    startRecorder() {
      recorder.start().then(
        () => {},
        (error) => {
          // 出错了
          console.log(`${error.name} : ${error.message}`);
        }
      );
    },

    // 暂停录音
    pauseRecorder() {
      recorder.pause();
    },
    // 结束录音
    stopRecorder() {
      let toltime = recorder.duration; //录音总时长
      if (toltime < 60) {
        this.pauseRecorder();
        console.log(toltime);
        alert("录制不可以少于一分钟", "已暂停请继续录制");
        return;
      } else {
        recorder.stop();
      }
    },
    getPermission() {
      Recorder.getPermission().then(
        () => {
          console.log("11111111111111111");
        },
        (error) => {
          console.log(`${error.name} : ${error.message}`);
        }
      );
    },

    async removevoiceById(row) {
      // 弹框询问用户是否删除数据
      const confirmResult = await this.$confirm(
        "此操作将永久删除该语音, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (confirmResult !== "confirm") {
        return this.$message.info("已取消删除");
      }
      removeVoice(row.id).then((res) => {
        console.log(res, 55555555555555);
        this.$message.success("删除语音成功！");
        // res.rank = 4;
        // res.label = res.TeachingTime;
        this.hgh(row.id);
      });
    },
  },
};
</script>
<style lang="less" scoped></style>

<style scoped>
.qwe:hover {
  width: 90px;
  /* height: 90px; */
  border: 1px solid rgb(45, 183, 245);
}
.qwe {
  /* flex: 1; */
  border: 1px solid rgb(255, 255, 255);
}
.qaz {
  display: flex;
  flex-wrap: wrap;
}
.zxc {
  flex: 1;
  display: flex;
}
.el-icon-plus {
  width: 90px;
  height: 90px;
  text-align: center;
  line-height: 90px;
  font-size: 30px;
  border: 1px solid #f3f3f3;
}
.content {
  /* display: flex; */
}
.content1 {
  /* flex: 1; */
  /* margin: 30px; */
}
/* .content1:hover {
  border: 1px solid rgb(45, 183, 245);
} */
</style>
